package com.dinadi.yidi.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.LvProductDetailsAdpater;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.bean.MyCouponsStateRequestEntity;
import com.dinadi.yidi.bean.OrderDetailsBean;
import com.dinadi.yidi.bean.OrderDetailsRequest;
import com.dinadi.yidi.bean.SkuListBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.ui.view.CommonDialogUtils2;
import com.dinadi.yidi.ui.view.MyListView;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.pingplusplus.android.Pingpp;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * author: JiaYu.He
 * Date: 2017/7/10    确认送礼订单页面
 * Time: 10:55
 */
public class GiveGiftOrderDetailsActivity extends BaseActivity {
    private View view;
    private TextView tvTitle;
    private TextView    tv_product_nums;
    private TextView product_price, tv_product_freight, total_product, favorable_price, tv_coupon, tv_coupon_price;
    private ImageView confirm_purchase;
    private EditText edit_remarks;
    private RadioGroup rg_payment_method;
    private RadioButton rb_zhifubao, rb_weixin;
    private RelativeLayout see_delivery_address, clip_coupons;
    private MyListView lv_product_details;
    private CommonDialogUtils2 noSetDialog;
    private LvProductDetailsAdpater lv_adapter;
    private List<OrderDetailsRequest> dataList = new ArrayList<>();
    private OrderDetailsRequest orderDetailsRequestBean;
    private String userId, token;
    private String userCouponId, productTitle,coverImg;
    /*地址信息*/
    private String  nameValue, skuId, quantity, payType;
    private String orderId, totalPrice;
    private String id;
    private String isShoppingCart, cartItemIds;


    @Override
    protected View getLayout() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        view = LayoutInflater.from(GiveGiftOrderDetailsActivity.this).inflate(R.layout.activity_order_details, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        tvTitle.setText(R.string.text_confirm_order);
        confirm_purchase = (ImageView) view.findViewById(R.id.confirm_purchase);
        rg_payment_method = (RadioGroup) view.findViewById(R.id.rg_payment_method);
        rb_zhifubao = (RadioButton) view.findViewById(R.id.rb_zhifubao);
        rb_weixin = (RadioButton) view.findViewById(R.id.rb_weixin);
        see_delivery_address = (RelativeLayout) view.findViewById(R.id.see_delivery_address);
        see_delivery_address.setVisibility(View.GONE);
        tv_product_nums = (TextView) view.findViewById(R.id.tv_product_nums);
        product_price = (TextView) view.findViewById(R.id.product_price);
        tv_product_freight = (TextView) view.findViewById(R.id.tv_product_freight);
        total_product = (TextView) view.findViewById(R.id.total_product);
        edit_remarks = (EditText) view.findViewById(R.id.edit_remarks);
        clip_coupons = (RelativeLayout) view.findViewById(R.id.clip_coupons);
        favorable_price = (TextView) view.findViewById(R.id.favorable_price);
        tv_coupon = (TextView) view.findViewById(R.id.tv_coupon);
        tv_coupon_price = (TextView) view.findViewById(R.id.tv_coupon_price);
        lv_product_details = (MyListView) view.findViewById(R.id.lv_product_details);
        lv_adapter = new LvProductDetailsAdpater(GiveGiftOrderDetailsActivity.this, dataList);
        lv_product_details.setAdapter(lv_adapter);
        orderDetailsRequestBean = new OrderDetailsRequest();

        payType = "2";
        rb_zhifubao.setChecked(true);
        rg_payment_method.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rb_zhifubao.getId()) {
                    payType = "2";
                } else if (checkedId == rb_weixin.getId()) {
                    payType = "1";
                }
            }
        });
        //注册EventBus  接收页面
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initListener() {
        registerClickListener(confirm_purchase, see_delivery_address, clip_coupons);

    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(this).getString("userId");
            token = SharePreferencesHelper.getInstance(this).getString("token");
            SharePreferencesHelper.getInstance(this).putString("isRefresh", "no");
        }
    }

    @Override
    protected void initData() {
        SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("recipients", "");
        SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("phone", "");
        SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("addressArea", "");
        userId = SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).getString("userId");
        token = SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).getString("token");

        Intent intent = getIntent();
        nameValue = intent.getStringExtra("nameValue");
        quantity = intent.getStringExtra("quantity");
        skuId = intent.getStringExtra("skuId");
        confirmChoice();


    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.confirm_purchase:
                  /*确认购买*/

                   SkuListBean bean = new SkuListBean();
                    bean.setUserId(userId);
                    bean.setSkuId(skuId);
                    bean.setQuantity(quantity);
                    bean.setToken(token);
                    bean.setNameValue(nameValue);
                    bean.setPayType(payType);
                    bean.setRemark(edit_remarks.getText().toString());
                    bean.setUserCouponId(userCouponId);
                    CommonInterface confirmSelectionInterface = new CommonInterface(GiveGiftOrderDetailsActivity.this, purchaseHttpListener);
                    confirmSelectionInterface.getInterface("16005", JSON.toJSONString(bean));


                break;
            case R.id.clip_coupons:
                /*使用优惠券*/
                Intent intent = new Intent(GiveGiftOrderDetailsActivity.this, MyCouponsStateActivity.class);
                intent.putExtra("skuId", skuId);
                intent.putExtra("quantity", quantity);
                intent.putExtra("cartItemIds", cartItemIds);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /*购买商品信息*/
    private void confirmChoice() {
        SkuListBean bean = new SkuListBean();
        bean.setSkuId(skuId);
        bean.setQuantity(quantity);
        bean.setToken(token);
        bean.setNameValue(nameValue);
        bean.setUserCouponId(userCouponId);
        CommonInterface confirmSelectionInterface = new CommonInterface(GiveGiftOrderDetailsActivity.this, httpListener);
        confirmSelectionInterface.getInterface("16002", JSON.toJSONString(bean));
    }



    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            dataList.clear();
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {

                String orderDetail = JsonUtil.getFieldValue(response, "orderDetail");
                 coverImg = JsonUtil.getFieldValue(orderDetail, "coverImg");
                String nameValue = JsonUtil.getFieldValue(orderDetail, "nameValue");
                String productId = JsonUtil.getFieldValue(orderDetail, "productId");
                 productTitle = JsonUtil.getFieldValue(orderDetail, "productTitle");
                String quantity = JsonUtil.getFieldValue(orderDetail, "quantity");
                String unitPrice = JsonUtil.getFieldValue(orderDetail, "unitPrice");
                String payPrice = JsonUtil.getFieldValue(response, "payPrice");
                String postage = JsonUtil.getFieldValue(response, "postage");
                totalPrice = JsonUtil.getFieldValue(response, "totalPrice");
                String originalPrice = JsonUtil.getFieldValue(orderDetail, "originalPrice");

//                ImageUtils.loadImageView(OrderDetailsActivity.this, coverImg, img_product);
//                tv_product_name.setText(productTitle);
//                tv_product_price.setText("￥" + unitPrice);
//                tv_product_attribute.setText("已选：" + nameValue);
//                tv_product_num.setText("x" + quantity);
                orderDetailsRequestBean.setCoverImg(coverImg);
                orderDetailsRequestBean.setNameValue(nameValue);
                orderDetailsRequestBean.setProductTitle(productTitle);
                orderDetailsRequestBean.setQuantity(quantity);
                orderDetailsRequestBean.setUnitPrice(unitPrice);
                orderDetailsRequestBean.setOriginalPrice(originalPrice);
                dataList.add(orderDetailsRequestBean);
                lv_adapter.notifyDataSetChanged();

                tv_product_nums.setText("共" + quantity + "件产品");
                /*商品价格数量总计*/
                product_price.setText("￥" + totalPrice);
                tv_product_freight.setText("￥" + postage);
                /*总价格*/
                total_product.setText("￥" + payPrice);

                String couponPrice = JsonUtil.getFieldValue(response, "couponPrice");
                if (!couponPrice.equals("0")) {
                    favorable_price.setText("- ￥" + couponPrice);
                    tv_coupon_price.setText("- ￥" + couponPrice);
                    tv_coupon.setVisibility(View.VISIBLE);
                    tv_coupon_price.setVisibility(View.VISIBLE);
                } else {
                    tv_coupon.setVisibility(View.GONE);
                    tv_coupon_price.setVisibility(View.GONE);
                }

            } else {
                ToastUtil.showToast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("加载失败");
        }
    };


    /*确认购买*/
    HttpListener purchaseHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                orderId = JsonUtil.getFieldValue(response, "orderIds");
                /*获取ping++支付Charge*/
                pingCharge();

            } else {
                ToastUtil.showToast(errMsg);
            }

        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    private void pingCharge() {
        OrderDetailsBean bean = new OrderDetailsBean();
        bean.setOrderIds(orderId);
        bean.setToken(token);
        bean.setClientIp("0.0.0.0");
        bean.setPayType(payType);
        CommonInterface commonInterface = new CommonInterface(GiveGiftOrderDetailsActivity.this, pingHttpListener);
        commonInterface.getInterface("16014", JSON.toJSONString(bean));
    }

    HttpListener pingHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String charge = JsonUtil.getFieldValue(response, "charge");
                id = JsonUtil.getFieldValue(charge, "id");
                //参数一：Activity 表示当前调起支付的Activity
                //参数二：data 表示获取到的charge或order的JSON字符串
                Pingpp.createPayment(GiveGiftOrderDetailsActivity.this, charge);

            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");
            /* 处理返回值
             * "success" - 支付成功
             * "fail"    - 支付失败
             * "cancel"  - 取消支付
             * "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
             * "unknown" - app进程异常被杀死(一般是低内存状态下,app进程被杀死)
             */
                if (result.equals("success")) {
                    OrderDetailsBean bean = new OrderDetailsBean();
                    bean.setOrderIds(orderId);
                    bean.setPayType(payType);
                    bean.setToken(token);
                    bean.setChargeId(id);
                    CommonInterface commonInterface = new CommonInterface(GiveGiftOrderDetailsActivity.this, orderStateHttpListener);
                    commonInterface.getInterface("16015", JSON.toJSONString(bean));
                    SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("isRefresh", "yes");
                    SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("isShoppingRefresh", "yes");
                    GiveGiftOrderDetailsActivity.this.finish();
                } else if (result.equals("fail")) {
                    ToastUtil.showToast("支付失败");
                } else if (result.equals("cancel")) {
                    ToastUtil.showToast("取消支付");
                    if (cartItemIds != null) {
                        Intent intent = new Intent();
                        intent.setClass(GiveGiftOrderDetailsActivity.this, MyOrderActivity.class);
                        intent.putExtra("orderId", orderId);
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent();
                        intent.setClass(GiveGiftOrderDetailsActivity.this, ProductOrderDetailsActivity.class);
                        intent.putExtra("orderId", orderId);
                        startActivity(intent);
                    }
                    SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("isRefresh", "yes");
                    SharePreferencesHelper.getInstance(GiveGiftOrderDetailsActivity.this).putString("isShoppingRefresh", "yes");
                    GiveGiftOrderDetailsActivity.this.finish();
                } else if (result.equals("invalid")) {
                    ToastUtil.showToast("支付插件未安装");
                } else if (result.equals("unknown")) {
                    ToastUtil.showToast("app进程异常被杀死");
                }
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息

            }
        }
    }

    HttpListener orderStateHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                String point = JsonUtil.getFieldValue(response, "point");
                ToastUtil.showToast("支付成功");
                Intent intent = new Intent(GiveGiftOrderDetailsActivity.this, GiftPaymentResultsActivity.class);
                intent.putExtra("cartItemIds", cartItemIds);
                intent.putExtra("orderId", orderId);
                intent.putExtra("totalPrice", totalPrice);
                intent.putExtra("point", point);
                intent.putExtra("giftName",productTitle);
                intent.putExtra("coverImg",coverImg);
                startActivity(intent);
                GiveGiftOrderDetailsActivity.this.finish();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
        }
    };

    public void onEventMainThread(MyCouponsStateRequestEntity bean) {

        if (bean != null) {

            userCouponId = bean.getId();

            if (isShoppingCart != null & "yes".equals(isShoppingCart)) {
                    /*结算购物车*/
            } else {
                confirmChoice();
            }
        }
    }

}
